<template>
  <div class="settings-page">
    <div class="page-header">
      <h1 class="page-title">Settings</h1>
      <p class="page-subtitle">System Configuration & Preferences</p>
    </div>

    <div class="settings-content">
      <a-tabs v-model:active-key="activeTab" tab-position="left">
        <!-- General Settings -->
        <a-tab-pane key="general" tab="General">
          <template #tab>
            <SettingOutlined /> General
          </template>
          <a-card title="General Settings" :bordered="false">
            <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-item label="System Name">
                <a-input v-model:value="systemSettings.systemName" />
              </a-form-item>
              <a-form-item label="Language">
                <a-select v-model:value="systemSettings.language" style="width: 200px">
                  <a-select-option value="en">English</a-select-option>
                  <a-select-option value="zh">中文</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="Theme">
                <a-radio-group v-model:value="systemSettings.theme">
                  <a-radio value="light">Light</a-radio>
                  <a-radio value="dark">Dark</a-radio>
                  <a-radio value="auto">Auto</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item :wrapper-col="{ offset: 6 }">
                <a-button type="primary" :loading="loading" @click="saveSystemSettings">Save Changes</a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-tab-pane>

        <!-- Notifications -->
        <a-tab-pane key="notifications" tab="Notifications">
          <template #tab>
            <BellOutlined /> Notifications
          </template>
          <a-card title="Notification Settings" :bordered="false">
            <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-item label="Email Notifications">
                <a-switch v-model:checked="notificationSettings.emailNotifications" />
              </a-form-item>
              <a-form-item label="Alert Notifications">
                <a-switch v-model:checked="notificationSettings.alertNotifications" />
              </a-form-item>
              <a-form-item label="Ticket Notifications">
                <a-switch v-model:checked="notificationSettings.ticketNotifications" />
              </a-form-item>
              <a-form-item :wrapper-col="{ offset: 6 }">
                <a-button type="primary" :loading="loading" @click="saveNotificationSettings">Save Changes</a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-tab-pane>

        <!-- Users -->
        <a-tab-pane key="users" tab="Users">
          <template #tab>
            <UserOutlined /> Users
          </template>
          <a-card title="User Management" :bordered="false">
            <a-button type="primary" style="margin-bottom: 16px">
              <PlusOutlined /> Add User
            </a-button>
            <a-table :columns="userColumns" :data-source="users" :pagination="false">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'role'">
                  <a-tag :color="record.role === 'admin' ? 'red' : 'blue'">
                    {{ record.role }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'actions'">
                  <a-space>
                    <a-button type="link" size="small">Edit</a-button>
                    <a-button type="link" size="small" danger>Delete</a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-tab-pane>

        <!-- Integrations -->
        <a-tab-pane key="integrations" tab="Integrations">
          <template #tab>
            <ApiOutlined /> Integrations
          </template>
          <a-card title="Third-party Integrations" :bordered="false">
            <a-empty v-if="integrations.length === 0" description="No integrations configured" />
            <a-list v-else :data-source="integrations">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta :title="item.name" :description="item.description">
                    <template #avatar>
                      <a-avatar style="background-color: #667eea">
                        {{ item.name.charAt(0) }}
                      </a-avatar>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-switch :checked="item.enabled" @change="toggleIntegration(item)" />
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  SettingOutlined,
  BellOutlined,
  UserOutlined,
  ApiOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue'
import {
  getSystemSettings,
  updateSystemSettings,
  getNotificationSettings,
  updateNotificationSettings,
  getIntegrations,
  updateIntegration,
  type SystemSettings,
  type NotificationSettings,
  type Integration,
} from '@/api/settings'
import { h } from 'vue'

const activeTab = ref('general')
const loading = ref(false)

const systemSettings = ref<SystemSettings>({
  systemName: 'DevOps SmartBot',
  language: 'en',
  theme: 'light',
})

const notificationSettings = ref<NotificationSettings>({
  emailNotifications: true,
  alertNotifications: true,
  ticketNotifications: false,
})

const userColumns = [
  { title: 'Name', dataIndex: 'name', key: 'name' },
  { title: 'Email', dataIndex: 'email', key: 'email' },
  { title: 'Role', dataIndex: 'role', key: 'role' },
  { title: 'Actions', key: 'actions' },
]

const users = ref([
  { key: '1', name: 'Admin', email: 'admin@example.com', role: 'admin' },
  { key: '2', name: 'John Doe', email: 'john@example.com', role: 'user' },
])

const integrations = ref<Integration[]>([])

const loadSystemSettings = async () => {
  try {
    const data = await getSystemSettings()
    systemSettings.value = data
  } catch (error) {
    console.error('Failed to load system settings:', error)
  }
}

const loadNotificationSettings = async () => {
  try {
    const data = await getNotificationSettings()
    notificationSettings.value = data
  } catch (error) {
    console.error('Failed to load notification settings:', error)
  }
}

const loadIntegrations = async () => {
  try {
    const response = await getIntegrations()
    integrations.value = response.data || []
  } catch (error) {
    console.error('Failed to load integrations:', error)
    integrations.value = []
  }
}

const saveSystemSettings = async () => {
  try {
    loading.value = true
    await updateSystemSettings(systemSettings.value)
    message.success('System settings saved successfully')
  } catch (error) {
    console.error('Failed to save system settings:', error)
    message.error('Failed to save system settings')
  } finally {
    loading.value = false
  }
}

const saveNotificationSettings = async () => {
  try {
    loading.value = true
    await updateNotificationSettings(notificationSettings.value)
    message.success('Notification settings saved successfully')
  } catch (error) {
    console.error('Failed to save notification settings:', error)
    message.error('Failed to save notification settings')
  } finally {
    loading.value = false
  }
}

const toggleIntegration = async (integration: Integration) => {
  try {
    if (!integration.id) return

    await updateIntegration(integration.id, {
      enabled: !integration.enabled,
    })

    integration.enabled = !integration.enabled
    message.success(`${integration.name} ${integration.enabled ? 'enabled' : 'disabled'}`)
  } catch (error) {
    console.error('Failed to toggle integration:', error)
    message.error('Failed to update integration')
  }
}

onMounted(async () => {
  await Promise.all([
    loadSystemSettings(),
    loadNotificationSettings(),
    loadIntegrations(),
  ])
})
</script>

<style scoped lang="scss">
.settings-page {
  height: 100%;
  overflow: auto;
  background: #f5f5f5;
}

.page-header {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;

  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }

  .page-subtitle {
    margin: 4px 0 0;
    color: #8c8c8c;
    font-size: 14px;
  }
}

.settings-content {
  padding: 24px;

  :deep(.ant-tabs-card) {
    background: white;
    border-radius: 8px;
  }
}
</style>
